<template>
  <MainSlot>
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" :unfoldFlag="unfoldFlag" :key="updateKey"
        @search="search" @isUnfold="(v) => {
          unfoldFlag = v;
        }
          ">
      </SearchForm>
    </template>
    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:table>
      <TableData :tableThead="tableThead" v-if="resetTable" :config="table_config" :dataList="tableData"
        :loading="loading" @selection-change="selectionChange">
      </TableData>
    </template>
    <template v-slot:pagination>
      <!-- <Pagination @current-change="handleCurrentChange" :page="page" :total="total">
      </Pagination> -->
      <el-pagination @size-change="(e) => { handleSizeChange(e), customSize = e }" @current-change="handleCurrentChange"
        :current-page="page" :page-sizes="[10, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, customSize]"
        :page-size="pageSize" layout="total,slot, sizes, prev, pager, next, jumper" background :total="total">
        <template #default>
          <el-input type="number" style="width: 150px;" v-model="customSize" placeholder="" @change="() => {
            customSize = customSize < 1 ? customSize = 1 : Math.floor(customSize)
            handleSizeChange(customSize);
          }"><template slot="append">条/页</template></el-input>
        </template>
      </el-pagination>
    </template>
    <template v-slot:dialogModule>
      <waterAddEdit v-model="addEditShow" :stordocList="stordocList" :fishPondObj="fishPondObj"
        :currentItem="currentItem" @close="closeDia" @reflash="getTableList" />
      <waterImport v-model="importShow" @close="closeDia" @reflash="getTableList" />
    </template>
  </MainSlot>
</template>
<script>
import MainSlot from "@/components-production-management/MainSlot";
import Pagination from "@/components-production-management/Pagination";
import BtnSlot from "@/components-production-management/BtnSlot";
import waterAddEdit from "./components/waterAddEdit";
import waterImport from "./components/waterImport";
import ncBasicInfoApi from "@/api/nc-basic-info/index";
import ncWaterQualityApi from "@/api/module/ncWaterQuality";
import TableData from "@/components-production-management/TableData";
import SearchForm from "@/components-production-management/SearchForm";
import FishPondApi from "@/api/basic-info-manage/fishPond";
import { mymixin } from "@/utils/mixin";
export default {
  mixins: [mymixin],
  components: {
    MainSlot,
    Pagination,
    BtnSlot,
    waterAddEdit,
    TableData,
    SearchForm,
    waterImport,
  },
  data() {
    return {
      currentItem: null,
      resetTable: true,
      // 配置项
      table_config: {
        isCheckBox: true,
        isOperation: true,
        // 表格操作列
        operation: {
          label: "操作",
          width: "300",
          cols: [
            {
              label: "编辑",
              type: "primary",
              flag: "edit",
              handleRow: this.handleRow,
            },
            {
              label: "删除",
              type: "danger",
              flag: "del",
              handleRow: this.handleRow,
            }
          ],
        },
      },
      formItemList: [
        {
          label: "塘号",
          type: "select",
          selectOptions: [],
          param: "ncWarehouseidLists",
          defaultSelect: "", // 下拉框默认选中项
          multiple: true,
          isShow: true,
          collapseTags: true,
        },
        {
          label: "日期查询",
          type: "daterange",
          defaultSelect: [],
          param: "dateTime",
          isShow: true,
        },
      ],
      unfoldFlag: false,
      tableThead: [
        {
          isShow: true,
          prop: "accumulationDate",
          label: "日期",
        },
        {
          isShow: true,
          prop: "ncWarehousename",
          label: "塘号",
        },
        {
          isShow: true,
          prop: "ph_NEW",
          label: "PH",
        },
        {
          isShow: true,
          prop: "oxygen_NEW",
          label: "溶解氧",
        },
        {
          isShow: true,
          prop: "temperature_NEW",
          label: "水温",
        },
        {
          isShow: true,
          prop: "nitrogen_NEW",
          label: "氨氮",
        },
        {
          isShow: true,
          prop: "subsalt_NEW",
          label: "亚盐",
        },
      ],
      btnList: ["add", "import", "export", "delete"],
      addEditShow: false,
      tableData: [],
      loading: false,
      page: 1,
      total: 0,
      pageSize: 100,
      customSize: 100,
      stordocList: [],
      updateKey: 0,
      filterData: {},
      fishPondObj: {},
      importShow: false,
    };
  },
  created() {
    this.getTableList();
    this.initData()
  },
  mounted() {
    if (this.$route.path == '/water-quality-report') {
      this.btnList = ["export"];
      this.table_config = {};
      this.$set(this, 'table_config', {})
      this.resetTable = false;
      this.$nextTick(() => {
        this.resetTable = true;
      })
    } else {
      this.btnList = ["add", "import", "export", "delete"]
    }
  },
  methods: {
    async initData() {
      this.fishPondObj = {};
      let { data: fishPondList } = await FishPondApi.queryByCondition({})
      fishPondList.forEach(e => {
        this.fishPondObj[e.ncWarehouseid] = e.fishPondId
      })
      this.queryStordoc();
    },
    handleRow(rowData, item) {
      if (item.flag == "del") {
        this.btnDelete([rowData]);
      } else if (item.flag == "edit") {
        let obj = JSON.parse(JSON.stringify(rowData));
        this.currentItem = obj
        this.addEditShow = true;
      }
    },
    // 多选方法
    selectionChange(val) {
      this.selectList = val || []
    },
    btnDelete(deleteList = [], key = 'waterQualityId') {
      let list = []
      let delList = deleteList.length ? deleteList : this.selectList || []
      if (delList.length) {
        delList.forEach(item => {
          list.push(item[key])
        })
        console.log(list)
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let res = await ncWaterQualityApi.delListById(list);
          if (res.success) {
            this.$message.success(res.message || '删除成功');
            this.getTableList();
          } else {
            this.$message.warning(res.message || '删除失败');
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      } else {
        this.$message({
          type: 'info',
          message: '请选择需要删除的数据'
        });
      }
    },
    search(data) {
      this.filterData = JSON.parse(JSON.stringify(data));
      this.page = 1;
      this.getTableList();
    },
    getTableList() {
      const { page, pageSize, filterData } = this;
      const paylod = {
        page,
        size: pageSize,
      };
      const entity = {};
      if (filterData.dateTime && filterData.dateTime.length > 0) {
        entity.startDateTime = filterData.dateTime[0] + " 00:00:00";
        entity.endDateTime = filterData.dateTime[1] + " 23:59:59";
      }
      if (filterData.ncWarehouseidLists) {
        entity.ncWarehouseidLists = filterData.ncWarehouseidLists.toString();
      }
      paylod.entity = entity;
      this.loading = true;
      ncWaterQualityApi
        .queryPageByCondition(paylod)
        .then((res) => {
          if (res.success) {
            const { data } = res;
            this.tableData = data.content;
            this.total = data.totalElements;
            this.tableData.forEach(item => {
              for (let key in item) { item[key + '_NEW'] = item[key] || '/' }
              return { ...item }
            })
            if (res.data.content.length === 0 && this.page !== 1) {
              this.page--;
              this.getTableList();
            }
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    queryStordoc() {
      ncBasicInfoApi.queryStordoc({}).then((res) => {
        this.stordocList = res.data;
        this.formItemList[0].selectOptions = this.stordocList.map((data) => {
          return {
            text: data.name,
            value: data.code,
          };
        });
        this.updateKey++;
      });
    },
    getBtnEvent(v) {
      this["btn" + this.capitalizeFirstLetter(v)]();
    },
    btnAdd() {
      this.currentItem = null;
      this.addEditShow = true;
    },
    btnExport() {
      const { filterData } = this;
      const entity = {};
      if (filterData.dateTime && filterData.dateTime.length > 0) {
        entity.startDateTime = filterData.dateTime[0] + " 00:00:00";
        entity.endDateTime = filterData.dateTime[1] + " 23:59:59";
      }
      if (filterData.ncWarehouseidLists) {
        entity.ncWarehouseidLists = filterData.ncWarehouseidLists.toString();
      }
      ncWaterQualityApi.reportWaterQuality({
        page: this.page,
        size: this.pageSize,
        entity: { ...entity }
      }).then((res) => {
        this.getFileNameAndDownload(res);
      });
    },
    btnImport() {
      this.importShow = true;
    },
    capitalizeFirstLetter(str) {
      if (!str) return "";

      // 将字符串的第一个字符转换为大写，剩余的字符保持不变
      return str.charAt(0).toUpperCase() + str.slice(1);
    },
    handleCurrentChange(page) {
      this.page = page;
      this.getTableList();
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.getTableList();
    },
    closeDia() {
      this.addEditShow = false;
      this.importShow = false;
      this.getTableList();
    },
  },
};
</script>
<style lang="scss" scoped></style>
